package cn.jinjimi.app.main.widget;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.TextView;

import cn.jinjimi.app.R;

/**
 * Created by lforxeverc on 2017/2/4.
 */

public class MatchTextView extends TextView {
    public MatchTextView(Context context) {
        this(context, null);
    }

    public MatchTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MatchTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setText(String string, String matcher) {
        setText(string, matcher, ContextCompat.getColor(getContext(), R.color.text_orange));
    }

    public void setText(String string, String matcher, int matchColor) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(string);
        if (!TextUtils.isEmpty(matcher) &&
                !TextUtils.isEmpty(string) &&
                string.toLowerCase().contains(matcher.trim().toLowerCase())) {
            int index = string.toLowerCase().indexOf(matcher.trim().toLowerCase());
            ForegroundColorSpan span = new ForegroundColorSpan(matchColor);
            spannableStringBuilder.setSpan(span, index, index + matcher.trim().length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
        }
        setText(spannableStringBuilder);
    }
}
